/**
 * Created by webhugo on 11/25/16.
 */

const db = require("../../model/index");
const Course = db.models.Course;
const Comment = db.models.Comment;
const responser = require('../../lib/responser');
const auth = require('../../helper/auth');
const utilx = require('../../lib/utilx');

module.exports = router => {
    /**
     * id 是 courseId
     */
    router.post('/course/addComment/:id', async(ctx, next) => {
        let id = ctx.params.id;
        let user = ctx.currentUser;
        user = user ? user : (await auth.user(ctx));
        // var user = {id:1};//test
        let text = utilx.PostCtx(ctx, "text");
        let type = parseInt(utilx.PostCtx(ctx, "type"));
        if (!id || !user || !text || !type) {
            responser.catchErr(ctx, "params miss or user has not logined", 0);
            return;
        }
        try {
            if (type == 1)
                await Comment.create({
                    text,
                    type: type,
                    UserId: user.id,
                    CourseId: id
                })
        } catch (e) {
            responser.catchErr(ctx, e);
            return;
        }
        responser.success(ctx);
        return;
    });
    /**
     * id 是 commentId
     */
    router.post('/course/delComment/:id', async(ctx, next) => {
        let id = ctx.params.id;
        let user = await auth.user(ctx);
        if (!id || !user) {
            responser.catchErr(ctx, "params miss or user has not logined", 0);
            return;
        }
        try {
            await Comment.destroy({
                where: {
                    id: id,
                    UserId: user.id
                }
            })
        } catch (e) {
            responser.catchErr(ctx, e);
            return;
        }
        responser.success(ctx, count);
        return;
    })
};